package cn.com.dhcc.turbo.service.exch;

import java.io.StringReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;

import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.util.Status;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.dao.exch.ExchRelDao;
import cn.com.dhcc.turbo.dao.registry.NodeInfoDao;
import cn.com.dhcc.turbo.dao.registry.OrgInfoDao;
import cn.com.dhcc.turbo.entity.exch.ExchRel;
import cn.com.dhcc.turbo.entity.exch.NodeLayout;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.NodePermission;
import cn.com.dhcc.turbo.service.registry.LocalConfCallBack;
import cn.com.dhcc.turbo.service.registry.sync.SyncCallBack;

/**
 * 交换关系service
 * 
 * @日期：2014-8-6 上午10:57:54
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Service
public class ExchRelService extends BaseService {
	@SuppressWarnings("deprecation")
	Logger logger = Log.getDetachLogger(LOGTYPE.TURBO);
	@Autowired
	private ExchRelDao exchRelDao;
	@Autowired
	private NodeInfoDao nodeInfoDao;
	@Autowired
	private OrgInfoDao orgInfoDao;
	@Autowired
	LocalConfCallBack localConfCallBack;

	/**
	 * 获取与节点进行数据交换的全部子节点列表 包含有关系节点和管理范围内的节点
	 * 
	 * @param nodeId
	 *当前节点ID
	 * @return
	 * @throws DaoException
	 */
	public List<NodeInfo> getAllExchNodeList(String nodeId)
			throws ServiceException {
		try {
			return exchRelDao.getAllExchNodeList(nodeId);
		} catch (DaoException e) {
			throw new ServiceException("获取交换关系失败", e);
		}
	}

	/**
	 * 通过节点id返回交换关系
	 * 
	 * @param nodeId
	 * @return
	 * @throws ServiceException
	 */
	public List<ExchRel> getAllExchByNodeId(String nodeId)
			throws ServiceException {
		try {
			return exchRelDao.getAllExchByNodeId(nodeId);
		} catch (DaoException e) {
			throw new ServiceException("获取交换关系失败", e);
		}

	}

	/**
	 * 节点树初始化
	 * isDrag　是否可拖动 isLeaf	是否有子节点
	 * @return
	 * @throws ServiceException
	 */
	public String getRootNodeTree() throws ServiceException {
		StringBuffer nodeTreeData = new StringBuffer();
		try {
			boolean rootIsDrag = false;
//			boolean rootIsLeaf = false;
			boolean rootIsAdmin = false;
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			if(localNode !=null){
				NodePermission permission = orgInfoDao.getPermission(localNode.getNodeCode().substring(0,6));
				NodeInfo root = nodeInfoDao.getNodeInfoByPid(NodeInfoParam.MWR_NODE_PID);
				nodeTreeData.append("<TreeView>");
				nodeTreeData.append("<Node ");
				nodeTreeData.append(" nodeName='").append(root.getNodeName()).append("' ");
				nodeTreeData.append(" nodeId='").append(root.getId()).append("' ");
				nodeTreeData.append(" parentId='").append(root.getPid()).append("' ");
				if(root.getId().equals(localNode.getId())){
					rootIsDrag = true;
				}
				nodeTreeData.append(" isDrag='").append(rootIsDrag).append("' ");
				//是否为管理节点
				if(root.getId().equals(localNode.getId())){
					rootIsAdmin = true;
				}
				nodeTreeData.append(" isAdmin='").append(rootIsAdmin).append("' ");
				nodeTreeData.append(" isBranch='").append(true).append("' >");
				
				List<NodeInfo> list = nodeInfoDao.getAllList(root.getId());
				for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
					NodeInfo vo = iterator.next();
					boolean isDrag = false;
					boolean isBranch = false;
					boolean isAdmin = false;
					nodeTreeData.append("<Node ");
					nodeTreeData.append(" nodeName='").append(vo.getNodeName()).append("' ");
					nodeTreeData.append(" nodeId='").append(vo.getId()).append("' ");
					nodeTreeData.append(" parentId='").append(vo.getPid()).append("' ");
					if(vo.getId().equals(localNode.getId()) || (permission != null && permission.getRegionCodesToMgr().indexOf(vo.getNodeCode().substring(0,6))!=-1)){
						isDrag = true;
					}
					nodeTreeData.append(" isDrag='").append(isDrag).append("' ");
					//是否为管理节点
					if(vo.getId().equals(localNode.getId())){
						isAdmin = true;
					}
					
					nodeTreeData.append(" isAdmin='").append(isAdmin).append("' ");
					if(Integer.parseInt(vo.getCont())>0){
						isBranch = true;
					}
					nodeTreeData.append(" isBranch='").append(isBranch).append("' >");
					if(vo.getId().equals(localNode.getId())){
						nodeTreeData.append(nodeTree(localNode.getId()));
					}
					nodeTreeData.append("</Node> ");
				}
				nodeTreeData.append("</Node>");
				nodeTreeData.append("</TreeView>");
			}
		} catch (DaoException e) {
			throw new ServiceException("获取节点树失败", e);
		}
		return nodeTreeData.toString();
	}

	/**
	 * 获取节点树点击，加载子节点树
	 * 
	 * @param id
	 *　父节点id
	 * @return
	 * @throws ServiceException
	 */
	public String nodeTree(String id) throws ServiceException {
		StringBuilder nodeTreeData = new StringBuilder();
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			if(localNode!=null){
				NodePermission permission = orgInfoDao.getPermission(localNode.getNodeCode().substring(0,6));
				List<NodeInfo> list = nodeInfoDao.getAllList(id);
				for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
					NodeInfo vo = iterator.next();
					boolean isDrag = false;
					boolean isBranch = false;
					boolean isAdmin = false;
					nodeTreeData.append("<Node ");
					nodeTreeData.append(" nodeName='").append(vo.getNodeName()).append("' ");
					nodeTreeData.append(" nodeId='").append(vo.getId()).append("' ");
					nodeTreeData.append(" parentId='").append(vo.getPid()).append("' ");
					if(vo.getId().equals(localNode.getId()) || (permission != null && permission.getRegionCodesToMgr().indexOf(vo.getNodeCode().substring(0,6))!= -1)){
						isDrag = true;
					}
					nodeTreeData.append(" isDrag='").append(isDrag).append("' ");
					//是否为管理节点
					if(vo.getId().equals(localNode.getId())){
						isAdmin = true;
					}
					nodeTreeData.append(" isAdmin='").append(isAdmin).append("' ");
					
					if(Integer.parseInt(vo.getCont())>0){
						isBranch = true;
					}
					nodeTreeData.append(" isBranch='").append(isBranch).append("' >");
					nodeTreeData.append("</Node> ");
				}
			}
		} catch (DaoException e) {
			throw new ServiceException("获取节点树失败", e);
		}
		return nodeTreeData.toString();
	}
	/**
	 * 获取交换关系图
	 * @param nodeId
	 * @return
	 * @throws ServiceException
	 */
	public NodeLayout getNodeLayout(String nodeId)throws ServiceException {
		try {
			return exchRelDao.getNodeLayout(nodeId);
		} catch (DaoException e) {
			throw new ServiceException("获取交换关系图失败", e);
		}
	}
	/**
	 * 建立交换关系
	 * @param vo
	 * @throws ServiceException
	 */
	public Status createRelAndSync(ExchRel exchRel) {
		Status status = null;
		try {
			//先进行通道的建立然后再创建交换关系
			status = localConfCallBack.beforeCreateRel(exchRel);
			if(status.isSuccess()){
				addRelData(exchRel);
			}
			return status;
		} catch (ServiceException e) {
			status = new Status();
			status.setMsg("建立交换关系失败!");
			status.setSuccess(false);
		}
		return status;
	}
	/**
	 * 建立交换关系
	 * @param vo
	 * @throws ServiceException
	 */
	public void addRelData(ExchRel vo) throws ServiceException {
		try {
			//先进行通道的建立然后再创建交换关系
			exchRelDao.delete(vo.getNodeIdCreator(),vo.getNodeIdTo());
			exchRelDao.add(vo);
		} catch (DaoException e) {
			throw new ServiceException(" 建立交换关系失败", e);
		}
	}
	/**
	 * 删除交换关系
	 * @param vo
	 * @throws ServiceException
	 */
	public void delete(String creatorId,String toId) throws ServiceException {
		try {
			exchRelDao.delete(creatorId,toId);
		} catch (DaoException e) {
			throw new ServiceException(" 删除交换关系失败", e);
		}
	}
	
	/**
	 * 保存交换关系图
	 * @param vo
	 * @throws ServiceException
	 */
	public void addNodeLayout(NodeLayout vo) throws ServiceException {
		try {
			exchRelDao.addNodeLayout(vo);
		} catch (DaoException e) {
			throw new ServiceException(" 保存交换关系图失败", e);
		}
		
	}
	
	/**
	 * 修改交换关系图
	 * @param vo
	 * @throws ServiceException
	 */
	public void updateNodeLayout(NodeLayout vo) throws ServiceException {
		try {
			exchRelDao.updateNodeLayout(vo);
		} catch (DaoException e) {
			throw new ServiceException(" 保存交换关系图失败", e);
		}
		
	}
	/**
	 * 通过来节点id删除交换关系
	 * @param nodeId
	 * @throws ServiceException
	 */
	public void delExchRelByNodeId(String nodeId)throws ServiceException {
		try {
			exchRelDao.delExchRelByNodeId(nodeId);
		} catch (DaoException e) {
			throw new ServiceException(" 删除交换关系失败", e);
		}
	}
	
	/**
	 * 获取节点交换关系图xml
	 * @param nodeId　节点id
	 * @return
	 * @throws ServiceException
	 */
	public NodeLayout getNodeLayoutRelXML(String nodeId)throws ServiceException {
		NodeLayout vo = new NodeLayout();
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			NodeLayout nodeLayout = exchRelDao.getNodeLayout(localNode.getId());
			String rstVal = this.forSyncExchRelXML(nodeId, nodeLayout.getRelNodeLayout());
			vo = new NodeLayout();
			vo.setId(UUIDGenerator.getUUID());
			vo.setNodeId(nodeId);
			vo.setRelNodeLayout(rstVal);
		} catch (DaoException e) {
			throw new ServiceException("获取节点交换关系图失败", e);
		}
		return vo;
	}
	
	/**
	 * 同步时生成关系图xml（只包含节点信息）
	 * @param nodeId
	 * @param xmlDoc
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	private String forSyncExchRelXML(String nodeId, String xmlDoc) {
		StringBuilder exchRelXML = new StringBuilder();
		// 创建一个新的字符串
		StringReader read = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		try {
		//获得所有关系节点
//		 List<ExchRel> relList = exchRelDao.getAllExchByNodeId(nodeId);
		 // 通过输入源构造一个Document
		 Document doc = sb.build(source);
		 // 取的根元素
		 Element root = doc.getRootElement();
		 // 得到根元素所有子元素的集合
		 List jiedian = root.getChildren();
		 if(jiedian.size() > 0){
			 // 获得XML中的命名空间（XML中未定义可不写）
//			 Namespace ns = root.getNamespace();
//			 Element et = null;
			 /**
			 * 如要取<rel>下的子元素的名称
			 */
//			 et = (Element) jiedian.get(0);
			 StringBuilder nodes = new StringBuilder(); 
			 List node = root.getChildren("node");
			 for (int i = 0; i < node.size(); i++) {
				Element nodeEt = (Element) node.get(i);
				if(nodeId.equals(nodeEt.getAttributeValue("nodeId")) || (!nodeId.equals(nodeEt.getAttributeValue("nodeId")) && exchRelDao.check(nodeEt.getAttributeValue("nodeId"),nodeId) != null)){
					nodes.append("<node");
					nodes.append(" nodeId='").append(nodeEt.getAttributeValue("nodeId")).append("'");
					nodes.append(" name='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
					nodes.append(" label='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
					nodes.append(" type='").append(nodeEt.getAttributeValue("type")).append("'");
					nodes.append(" selected='").append(nodeEt.getAttributeValue("selected")).append("'");
					nodes.append(" x='").append(nodeEt.getAttributeValue("x")).append("'");
					nodes.append(" y='").append(nodeEt.getAttributeValue("y")).append("'");
					nodes.append(" isCurrent='").append(nodeEt.getAttributeValue("isCurrent")).append("'");
					nodes.append(" isEdit='").append(nodeEt.getAttributeValue("isEdit")).append("' />");
				}
			 }
			
			 exchRelXML.append("<rel>").append(nodes.toString()).append("</rel>");
		 	}else{
				exchRelXML.append(xmlDoc);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return exchRelXML.toString();
	}

	/**
	 * 关系图同步合并入库
	 * @param nodeLayoutRecv
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	public SyncCallBack mergeNodeLayout(NodeLayout nodeLayoutRecv){
		SyncCallBack callBack = new SyncCallBack();
		String xmlDoc = nodeLayoutRecv.getRelNodeLayout();
		StringBuilder exchRelXML = new StringBuilder();
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			NodeLayout nodeLayout = exchRelDao.getNodeLayout(localNode.getId());
			 StringBuilder nodes = new StringBuilder(); 
			if(nodeLayout == null){
				nodeLayout = new NodeLayout();
			}else{
				StringReader localRead = new StringReader(nodeLayout.getRelNodeLayout());
				InputSource localSource = new InputSource(localRead);
				SAXBuilder localSb = new SAXBuilder();
				Document localDoc = localSb.build(localSource);
				Element localRoot = localDoc.getRootElement();
				List<Element> localJiedian = localRoot.getChildren();
				
				 //本地
				 if(localJiedian.size() > 0){
//					 Element localEt = localJiedian.get(0);
						List<Element> localNodes = localRoot.getChildren("node");
					 //本地关系节点
					 for (int n1 = 0; n1 < localNodes.size(); n1++) {
						Element localNodeEt =  localNodes.get(n1);
						if(localNode.getId().equals(nodeInfoDao.get(localNodeEt.getAttributeValue("nodeId")).getPid())){
							nodes.append("<node");
							nodes.append(" nodeId='").append(localNodeEt.getAttributeValue("nodeId")).append("'");
							nodes.append(" name='").append(nodeInfoDao.get(localNodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
							nodes.append(" label='").append(nodeInfoDao.get(localNodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
							nodes.append(" type='").append(localNodeEt.getAttributeValue("type")).append("'");
							nodes.append(" selected='").append(localNodeEt.getAttributeValue("selected")).append("'");
							nodes.append(" x='").append(localNodeEt.getAttributeValue("x")).append("'");
							nodes.append(" y='").append(localNodeEt.getAttributeValue("y")).append("'");
							nodes.append(" isCurrent='").append(localNodeEt.getAttributeValue("isCurrent")).append("'");
							nodes.append(" mgrNode='").append(localNodeEt.getAttributeValue("mgrNode")).append("'");
							nodes.append(" isEdit='").append(true).append("' />");
						}
					 }
					}
			}
			// 创建一个新的字符串
			StringReader read = new StringReader(xmlDoc);
			
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			
		 // 通过输入源构造一个Document
			Document doc = sb.build(source);
			
			// 取的根元素
			Element root = doc.getRootElement();
			
			// 得到根元素所有子元素的集合
			List<Element> jiedian = root.getChildren();
			
		 // 获得XML中的命名空间（XML中未定义可不写）
		 /**
		 * 如要取<rel>下的子元素的名称
		 */
		 //上级
		 if(jiedian.size() > 0){
//			 Element et =  jiedian.get(0);
			 List<Element> node = root.getChildren("node");
			 //上级关系节点
			 for (int n2i = 0; n2i < node.size(); n2i++) {
				Element nodeEt =  node.get(n2i);
				nodes.append("<node");
				nodes.append(" nodeId='").append(nodeEt.getAttributeValue("nodeId")).append("'");
				nodes.append(" name='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
				nodes.append(" label='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
				nodes.append(" type='").append(nodeEt.getAttributeValue("type")).append("'");
				nodes.append(" selected='").append(nodeEt.getAttributeValue("selected")).append("'");
				nodes.append(" x='").append(nodeEt.getAttributeValue("x")).append("'");
				nodes.append(" y='").append(nodeEt.getAttributeValue("y")).append("'");
				nodes.append(" isCurrent='").append(nodeEt.getAttributeValue("isCurrent")).append("'");
				nodes.append(" mgrNode='").append(nodeEt.getAttributeValue("mgrNode")).append("'");
				nodes.append(" isEdit='").append(false).append("' />");
			 }
			 exchRelXML.append("<rel>").append(nodes.toString()).append("</rel>");
		 	}else{
				exchRelXML.append(xmlDoc);
			}
		 nodeLayout.setRelNodeLayout(exchRelXML.toString());
		 if(nodeLayout.getId() == null){
			 nodeLayout.setId(UUIDGenerator.getUUID());
			 nodeLayout.setNodeId(localNode.getId());
			 nodeLayout.setMtime(new Date());
			 exchRelDao.addNodeLayout(nodeLayout);
		 }else{
			 exchRelDao.updateNodeLayout(nodeLayout);
		 }
		 callBack.setResult(SUCCESSFAIL.SUCCESS);
	} catch (Exception e) {
		callBack.setResult(SUCCESSFAIL.FAIL);
		logger.error(e);
	}
	return callBack;
}
	
	/**
	 * 动态生成关系图
	 * @param xmlDoc
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public String forExchRelXML(String xmlDoc,String nodeId) {
		StringBuilder exchRelXML = new StringBuilder();
		// 创建一个新的字符串
		StringReader read = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		try {
		NodeInfo localNode = nodeInfoDao.getLocalNode();
		//获得所有关系节点
		 List<ExchRel> relList = exchRelDao.getAllExchByNodeId(nodeId);
		 // 通过输入源构造一个Document
		 Document doc = sb.build(source);
		 // 取的根元素
		 Element root = doc.getRootElement();
		 // 得到根元素所有子元素的集合
		 List jiedian = root.getChildren();
		 if(jiedian.size() > 0){
			 // 获得XML中的命名空间（XML中未定义可不写）
//			 Namespace ns = root.getNamespace();
//			 Element et = null;
			 /**
			 * 如要取<rel>下的子元素的名称
			 */
//			 et = (Element) jiedian.get(0);
			 StringBuilder nodes = new StringBuilder(); 
			 Map<String,String> map = new HashMap<String,String>();
			 List node = root.getChildren("node");
			 for (int i = 0; i < node.size(); i++) {
				Element nodeEt = (Element) node.get(i);
				NodeInfo nodevo = nodeInfoDao.get(nodeEt.getAttributeValue("nodeId"));
				if(nodevo == null){
						continue;
				}
				if(nodeId.equals(nodeEt.getAttributeValue("nodeId")) || (!nodeId.equals(nodeEt.getAttributeValue("nodeId")) && exchRelDao.check(nodeEt.getAttributeValue("nodeId"),nodeId) != null)){
					boolean isEdit = true;
					nodes.append("<node");
					nodes.append(" nodeId='").append(nodeEt.getAttributeValue("nodeId")).append("' ");
					nodes.append(" name='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("' ");
					nodes.append(" label='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("' ");
					nodes.append(" type='").append(nodeEt.getAttributeValue("type")).append("' ");
					nodes.append(" selected='").append(nodeEt.getAttributeValue("selected")).append("' ");
					nodes.append(" x='").append(nodeEt.getAttributeValue("x")).append("' ");
					nodes.append(" y='").append(nodeEt.getAttributeValue("y")).append("' ");
					nodes.append(" isCurrent='").append(nodeEt.getAttributeValue("isCurrent")).append("' ");
					if(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getPid().equals(localNode.getPid())){
						isEdit = false;
					}
					nodes.append(" isEdit='").append(isEdit).append("' />");
					map.put(nodevo.getId(), nodevo.getNodeName());
				}
			 }
			 StringBuilder lines = new StringBuilder();
			 for (int i = 0; i < relList.size(); i++) {
				 ExchRel	exchRel = relList.get(i);
				String fromNodeName = map.get(exchRel.getNodeIdCreator());
			 	String toNodeName = map.get(exchRel.getNodeIdTo());
				if(fromNodeName == null || toNodeName == null){
					continue;
				}
				boolean isEdit = false;
				lines.append("<line");
				lines.append(" name='").append(exchRel.getNodeIdCreator()).append("' ");
				lines.append(" fromNode='").append(exchRel.getNodeIdCreator()).append("' ");
				lines.append(" toNode='").append(exchRel.getNodeIdTo()).append("' ");
				lines.append(" fromIcon='").append(map.get(exchRel.getNodeIdCreator())).append("' ");
		    	lines.append(" toIcon='").append(map.get(exchRel.getNodeIdTo())).append("' ");
		    	if(nodeInfoDao.get(exchRel.getNodeIdCreator()).getPid().equals(localNode.getId()) && nodeInfoDao.get(exchRel.getNodeIdTo()).getPid().equals(localNode.getId())){
					isEdit = true;
		    	}
		    	lines.append(" isEdit='").append(isEdit).append("' />");
			 }
			
			 exchRelXML.append("<rel>").append(nodes.toString()).append(lines.toString()).append("</rel>");
		 	}else{
				exchRelXML.append(xmlDoc);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return exchRelXML.toString();
	}

	@SuppressWarnings({ "rawtypes" })
	public String forExchRelXMLAllNode(String xmlDoc) {
		String mwrPid= NodeInfoParam.MWR_NODE_PID;
		StringBuilder exchRelXML = new StringBuilder();
		// 创建一个新的字符串
		StringReader read = new StringReader(xmlDoc);
		// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
		InputSource source = new InputSource(read);
		// 创建一个新的SAXBuilder
		SAXBuilder sb = new SAXBuilder();
		try {
			 NodeInfo localNode = nodeInfoDao.getLocalNode();
			//获得所有关系节点
			 List<ExchRel> relList = exchRelDao.getAllExchRel();
			 // 通过输入源构造一个Document
			 Document doc = sb.build(source);
			 // 取的根元素
			 Element root = doc.getRootElement();
			 // 得到根元素所有子元素的集合
			 List jiedian = root.getChildren();
			 if(jiedian.size() > 0){
				 // 获得XML中的命名空间（XML中未定义可不写）
//				 Namespace ns = root.getNamespace();
//				 Element et = null;
				 /**
				 * 如要取<rel>下的子元素的名称
				 */
//				 et = (Element) jiedian.get(0);
				 StringBuilder nodes = new StringBuilder(); 
				 Map<String,String> map = new HashMap<String,String>();
				 List node = root.getChildren("node");
				 for (int i = 0; i < node.size(); i++) {
					 	boolean isEdit = false;
						Element nodeEt = (Element) node.get(i);
						NodeInfo nodevo = nodeInfoDao.get(nodeEt.getAttributeValue("nodeId"));
						if(nodevo == null){
							continue;
						}
						nodes.append("<node");
						nodes.append(" nodeId='").append(nodeEt.getAttributeValue("nodeId")).append("' ");
						nodes.append(" name='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("' ");
						nodes.append(" label='").append(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getNodeName()).append("' ");
						nodes.append(" type='").append(nodeEt.getAttributeValue("type")).append("' ");
						nodes.append(" selected='").append(nodeEt.getAttributeValue("selected")).append("' ");
						nodes.append(" x='").append(nodeEt.getAttributeValue("x")).append("' ");
						nodes.append(" y='").append(nodeEt.getAttributeValue("y")).append("' ");
						nodes.append(" isCurrent='").append(nodeEt.getAttributeValue("isCurrent")).append("' ");
						if(nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getPid().equals(localNode.getId()) || nodeInfoDao.get(nodeEt.getAttributeValue("nodeId")).getId().equals(localNode.getId())){
							isEdit = true;
						}
						nodes.append(" isEdit='").append(isEdit).append("' />");
						map.put(nodevo.getId(), nodevo.getNodeName());
				 }
				 StringBuilder lines = new StringBuilder();
				 for (int i = 0; i < relList.size(); i++) {
					boolean isEdit = false;
				 	ExchRel	exchRel = relList.get(i);
				 	String fromNodeName = map.get(exchRel.getNodeIdCreator());
				 	String toNodeName = map.get(exchRel.getNodeIdTo());
					if(fromNodeName == null || toNodeName == null){
						continue;
					}
					lines.append("<line");
					lines.append(" name='").append(exchRel.getNodeIdCreator()).append("' ");
					lines.append(" fromNode='").append(exchRel.getNodeIdCreator()).append("' ");
					lines.append(" toNode='").append(exchRel.getNodeIdTo()).append("' ");
					lines.append(" fromIcon='").append(fromNodeName).append("' ");
			    	lines.append(" toIcon='").append(toNodeName).append("' ");
					if(nodeInfoDao.get(exchRel.getNodeIdCreator()).getPid().equals(localNode.getId()) && nodeInfoDao.get(exchRel.getNodeIdTo()).getPid().equals(localNode.getId())){
						isEdit = true;
					}else if(localNode.getPid().equals(mwrPid) &&(nodeInfoDao.get(exchRel.getNodeIdCreator()).getPid().equals(mwrPid) || nodeInfoDao.get(exchRel.getNodeIdTo()).getPid().equals(mwrPid))){
						isEdit = true;
					}
					lines.append(" isEdit='").append(isEdit).append("' />");
				 }
				 exchRelXML.append("<rel>").append(nodes.toString()).append(lines.toString()).append("</rel>");
			 }else{
				exchRelXML.append(xmlDoc);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return exchRelXML.toString();
	}
	/**
	 * 删除节点保存关系图
	 * @param nodeId　节点id
	 */
	@SuppressWarnings({ "unchecked" })
	public void delNodeRelLayout(String nodeId){
		StringBuilder exchRelXML = new StringBuilder();
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			NodeLayout nodeLayout = exchRelDao.getNodeLayout(localNode.getId());
			if(nodeLayout == null){
				nodeLayout = new NodeLayout();
			}
			// 创建一个新的字符串
			StringReader localRead = new StringReader(nodeLayout.getRelNodeLayout());
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource localSource = new InputSource(localRead);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
//			SAXBuilder localSb = new SAXBuilder();
		 // 通过输入源构造一个Document
			Document localDoc = sb.build(localSource);
			// 取的根元素
			Element localRoot = localDoc.getRootElement();
			// 得到根元素所有子元素的集合
			List<Element> localJiedian = localRoot.getChildren();
		 // 获得XML中的命名空间（XML中未定义可不写）
		 /**
		 * 如要取<rel>下的子元素的名称
		 */
//			Element localEt = localJiedian.get(0);
		 
		 StringBuilder nodes = new StringBuilder(); 
		 
		 List<Element> localNodes = localRoot.getChildren("node");
		 //本地
		 if(localJiedian.size() > 0){
			 //本地关系节点
			 for (int n1 = 0; n1 < localNodes.size(); n1++) {
				Element localNodeEt =  localNodes.get(n1);
				if(!nodeId.equals(localNodeEt.getAttributeValue("nodeId"))){
					nodes.append("<node");
					nodes.append(" nodeId='").append(localNodeEt.getAttributeValue("nodeId")).append("'");
					nodes.append(" name='").append(nodeInfoDao.get(localNodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
					nodes.append(" label='").append(nodeInfoDao.get(localNodeEt.getAttributeValue("nodeId")).getNodeName()).append("'");
					nodes.append(" type='").append(localNodeEt.getAttributeValue("type")).append("'");
					nodes.append(" selected='").append(localNodeEt.getAttributeValue("selected")).append("'");
					nodes.append(" x='").append(localNodeEt.getAttributeValue("x")).append("'");
					nodes.append(" y='").append(localNodeEt.getAttributeValue("y")).append("'");
					nodes.append(" isCurrent='").append(localNodeEt.getAttributeValue("isCurrent")).append("'");
					nodes.append(" mgrNode='").append(localNodeEt.getAttributeValue("mgrNode")).append("'");
					nodes.append(" isEdit='").append(true).append("' />");
				}
			 }
			}
		 exchRelXML.append("<rel>").append(nodes.toString()).append("</rel>");
		 nodeLayout.setRelNodeLayout(exchRelXML.toString());
		 exchRelDao.updateNodeLayout(nodeLayout);
		} catch (Exception e) {
			logger.error(e);
		}
	}
}
